// import sqlite data into mongodb

let path = require('path');
let co = require('co');
let Promise = require('bluebird');
let async = require('async');
let pinyinUtils = require('./utils/pinyinUtils');

let sqlite3 = require('sqlite3').verbose();


let sqliteDBPath = path.resolve(__dirname, './database.db');

let sqliteDatabase = new sqlite3.Database(sqliteDBPath);

// connect mongodb
require('./models');

let offset = parseInt(process.argv[process.argv.length - 2]);
let totalCount = parseInt(process.argv[process.argv.length - 1]);
console.log(offset, totalCount);

const STEP = 10000;
let pos = offset;


querySqlite();

function querySqlite() {
    let limit = STEP;
    let isLast = false;
    if (pos + STEP >= offset + totalCount) {
        // last query
        limit = offset + totalCount - pos;
        isLast = true;
    }
    // let statement = sqliteDatabase.prepare(`SELECT * FROM items LIMIT ${limit} OFFSET ${pos}`);

    sqliteDatabase.all(`SELECT * FROM items LIMIT ${limit} OFFSET ${pos}`, function (err, rows) {
        if (err) {
            console.log(err);
            return;
        }

        if (rows.length === 0) {
            console.log('complete');
            sqliteDatabase.close();
            return;
        }
        let books = rows.map(function (row) {
            let book = JSON.parse(row.BookInfo);
            book.bookNum = row.BookNum;
            book.id = row.Id;
            // pinyin
            if (book.title) {
                book.titlePinyin = pinyinUtils.getModelFormat(book.title);
            }
            return book;
        });
        Book.create(books, function (err, bookResults) {
            if (err) {
                console.log(err);
                return;
            }
            pos += STEP;
            console.log('pos', pos);
            if (isLast) {
                console.log('complete');
                sqliteDatabase.close();
                return;
            }
            querySqlite();
        });
        // // book process
        // co.wrap(storeRowsGen)(rows)
        //     .then(function () {
        //         pos += STEP;
        //         console.log('pos', pos);
        //         if (isLast) {
        //             console.log('complete');
        //             sqliteDatabase.close();
        //         }
        //         querySqlite();
        //     })
        //     .catch(function (err) {
        //         console.log(JSON.stringify(err));
        //     });

    });


}

function* storeRowsGen(rows) {
    yield storeRows(rows);
}

function storeRows(rows) {
    return new Promise(function (resolve, reject) {
        if (!rows) {
            reject();
            return;
        }
        let current = 0;
        // store rows
        async.each(rows, function (row, cb) {
            let book = JSON.parse(row.BookInfo);
            book.bookNum = row.BookNum;
            book.id = row.Id;
            // pinyin
            if (book.title) {
                book.titlePinyin = pinyinUtils.getModelFormat(book.title);
            }
            // book process
            co.wrap(bookProcessGen)(book)
                .then(function () {
                    current++;
                    console.log(current);
                    cb();
                })
                .catch(function (err) {
                    console.log(book);
                    cb(err);
                });
        }, function (err) {
            if (err) {
                reject(err);
                return;
            }
            resolve();
        });

    });
}

// book process
function* bookProcessGen(book) {
    // // find book
    // let isbn = book.isbn10 || book.isbn13;
    // let bookResult = yield findBook(isbn);
    //
    // if (bookResult) {
    //     // book exist, update book
    //     let updateResult = yield updateBook(book);
    //     // console.log(updateResult);
    // } else {
    //     // book not exist
    //     let newBook = yield createBook(book);
    //     // console.log(newBook.toJSON());
    // }
    let newBook = yield createBook(book);
}

function findBook(isbn) {
    return new Promise(function (resolve, reject) {
        if (!isbn) {
            reject();
            return;
        }

        // Book.findOne({$or: [{isbn10: isbn}, {isbn13: isbn}]}, function (err, bookResult) {
        Book.findOne({$or: [{isbn10: isbn}, {isbn13: isbn}]}).exec(function (err, bookResult) {
            if (err) {
                reject(err);
                return;
            }
            resolve(bookResult);
            return;
        });
    });
}

// book update
function updateBook(book) {
    return new Promise(function (resolve, reject) {

        if (!book) {
            reject();
            return;
        }
        let isbn = book.isbn10 || book.isbn13;
        Book.update({$or: [{isbn10: isbn}, {isbn13: isbn}]}, book, {multi: true}, function (err, updateResult) {
            if (err) {
                reject(err);
                return;
            }
            resolve(updateResult);
            return;
        });
    });
}

// create book
function createBook(book) {
    return new Promise(function (resolve, reject) {

        if (!book) {
            reject();
            return;
        }

        Book.create(book, function (err, bookResult) {
            if (err) {
                reject(err);
                return;
            }
            resolve(bookResult);
            return;
        });
    });
}


